package com.k.activemq.openwire;

import com.k.activemq.ActiveMQUtils;
import com.k.activemq.MqConnectionEntity;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQBytesMessage;

import javax.jms.*;

public class Listener {
    public static void main(String[] args) throws JMSException {
        MqConnectionEntity et = MqConnectionEntity.newBuilder()
                .setUrl("tcp://localhost:61616")
                .setUsername("admin")
                .setPassword("admin")
                .setDestination("queue-ljwtest1")
                .setPubSubDomain(false)
                .build();

        // 1.connectionFactory
        ConnectionFactory factory = new ActiveMQConnectionFactory(et.getUrl());

        // 2. connection
        Connection connection = factory.createConnection(et.getUsername(), et.getPassword());
        connection.start();

        // 3. session  consumer.receive()方法调用会自动确认。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // 4. destination
        Destination dest = (et.getPubSubDomain()==true)? session.createTopic(et.getDestination()):session.createQueue(et.getDestination());

        // 5. consumer
        MessageConsumer consumer = session.createConsumer(dest);

        long start = System.currentTimeMillis();
        System.out.println("Waiting for messages...");
        while(true) {
            Message msg = consumer.receive();
            if( msg instanceof  TextMessage ) {
                System.out.println("Received TextMessage");
                String body = ((TextMessage) msg).getText();
                if( "SHUTDOWN".equals(body)) {
                    long diff = System.currentTimeMillis() - start;
                    System.out.println(String.format("Received %s in %.2f seconds", body, (1.0*diff/1000.0)));
                    break;
                } else{
                    System.out.println("Received msg:"+body);
                }
            } else if(msg instanceof BytesMessage){
                System.out.println("Received BytesMessage");
                ActiveMQBytesMessage receiveMsg = (ActiveMQBytesMessage) msg;
                String msgStr = ActiveMQUtils.byteMessageToString(receiveMsg);
                System.out.println("Received msg:"+msgStr);
            } else {
                System.out.println("Received msg:NoHandler");
            }
            // 自动确认
            msg.acknowledge();
        }
        //connection.close();
    }
}
